package cl.ucn.disc.biblio.refcluster.view;

// Adapted from: http://textareaappender.zcage.com/

import java.util.Properties;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

/**
 * Simple example of creating a Log4j appender that will write to a JTextArea.
 */
public class TextAreaAppender extends WriterAppender {

	static private JTextArea jTextArea = null;

	/** Set the target JTextArea for the logging information to appear. */
	static public void setTextArea(JTextArea jTextArea) {
		TextAreaAppender.jTextArea = jTextArea;
		TextAreaAppender textAreaAppender = new TextAreaAppender();
		textAreaAppender.addFilter(new Filter() {

			@Override
			public int decide(LoggingEvent event) {
				if (event.getLevel().equals(Level.INFO)) {
					return ACCEPT;
				} else {
					return DENY;
				}
			}
		});
		Logger.getRootLogger().addAppender(textAreaAppender);
		
		Properties logProperties = new Properties();
		logProperties.put("log4j.rootLogger", "INFO, CONSOLE, TEXTAREA");
		logProperties.put("log4j.appender.CONSOLE", "org.apache.log4j.ConsoleAppender"); // A standard console appender
		logProperties.put("log4j.appender.CONSOLE.layout", "org.apache.log4j.PatternLayout"); //See: http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
		logProperties.put("log4j.appender.CONSOLE.layout.ConversionPattern", "%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p]   %m%n");

		logProperties.put("log4j.appender.TEXTAREA", "cl.ucn.disc.biblio.refcluster.view.TextAreaAppender");  // Our custom appender
		logProperties.put("log4j.appender.TEXTAREA.layout", "org.apache.log4j.PatternLayout"); //See: http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html
		logProperties.put("log4j.appender.TEXTAREA.layout.ConversionPattern", "%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p]   %m%n");
		
		PropertyConfigurator.configure(logProperties);
		
		
	}

	@Override
	/**
	 * Format and then append the loggingEvent to the stored
	 * JTextArea.
	 */
	public void append(LoggingEvent loggingEvent) {
		if (this.layout != null) {
			final String message = this.layout.format(loggingEvent);

			// Append formatted message to textarea using the Swing Thread.
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					jTextArea.append(message);
				}
			});
		}
	}
}
